<template>
  <el-dialog
    :model-value="dialogVisible"
    title="批量创建"
    @close="$emit('close')"
    width="80%"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" ref="formRef">
      <el-table :data="formData.list">
        <el-table-column label="上级系统" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]parentId`"
              :rules="[{ required: true, message: '上级系统不能为空', trigger: 'change' }]"
            >
              <el-tree-select
                v-model="formData.list[scope.$index].parentId"
                :data="deptTree"
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'id',
                  isLeaf: 'leaf',
                  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
                }"
                check-strictly
                default-expand-all
                placeholder="请选择上级系统"
                value-key="deptId"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="系统名称" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]name`"
              :rules="[{ required: true, validator: valideName, trigger: 'blur' }]"
            >
              <ns-input v-model="formData.list[scope.$index].name" placeholder="请输入机构名称" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="所属区域" width="150px">
          <template #default="scope">
            <el-form-item :prop="`list[${scope.$index}]cityId`">
              <el-tree-select
                v-model="formData.list[scope.$index].cityId"
                :data="areaTree"
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'id'
                }"
                placeholder="请选择所属区域"
                value-key="id"
                node-key="id"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="详细地址" width="150px">
          <template #default="scope">
            <el-form-item :prop="`list[${scope.$index}]address`">
              <ns-input
                v-model="formData.list[scope.$index].address"
                placeholder="请输入详细地址"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="应用系统IP段" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]targetIps`"
              :rules="[{ required: false, validator: validateIp, trigger: 'blur' }]"
            >
              <ns-input
                v-model="formData.list[scope.$index].targetIps"
                placeholder="请输入应用系统IP段"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="显示排序" width="150px">
          <template #default="scope">
            <el-form-item :prop="`list[${scope.$index}]orderIndex`">
              <el-input-number
                v-model="formData.list[scope.$index].orderIndex"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="150px">
          <template #default="scope">
            <el-form-item :prop="`list[${scope.$index}]header`">
              <el-select
                v-model="formData.list[scope.$index].header"
                clearable
                placeholder="请输入负责人"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]phone`"
              :rules="[
                {
                  pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                  message: '请输入正确的手机号码',
                  trigger: 'blur'
                }
              ]"
            >
              <ns-input
                v-model="formData.list[scope.$index].phone"
                maxlength="11"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]email`"
              :rules="[
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
              ]"
            >
              <ns-input
                v-model="formData.list[scope.$index].email"
                maxlength="50"
                placeholder="请输入邮箱"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="150px">
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}]status`"
              :rules="[{ required: true, message: '状态不能为空', trigger: 'change' }]"
            >
              <el-select
                v-model="formData.list[scope.$index].status"
                clearable
                placeholder="请选择状态"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          width="150px"
          label="操作"
          show-overflow-tooltip
          min-width="150px"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              v-if="scope.$index == formData.list.length - 1"
              :icon="Plus"
              size="small"
              circle
              class="ml-12px"
              @click="addRow()"
            />

            <el-button
              v-if="formData.list.length > 1"
              :icon="Minus"
              size="small"
              circle
              class="ml-12px"
              @click="delRow(scope.$index)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="$emit('close')">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { Plus, Minus, Close } from '@element-plus/icons-vue'
import { CommonStatusEnum } from '@/utils/constants'
import { sysFilterMethod } from '@/utils/selectFilter'
import { defaultProps, handleTree } from '@/utils/tree'
import cloneDeep from 'lodash-es/cloneDeep'
import * as SystemApi from '@/api/system/infoSystem'
import * as UserApi from '@/api/system/user'
import * as AreaApi from '@/api/system/area'

const formRef = ref()
const areaTree = ref() //区域树形结构
const deptTree = ref() // 树形结构
const userList = ref([]) // 用户列表
const emit = defineEmits(['close'])
const props = defineProps({
  dialogVisible: {
    default: true,
    type: Boolean
  }
})
const formData = reactive({
  list: [
    {
      parentId: '',
      name: undefined,
      cityId: undefined,
      orderIndex: undefined,
      address: undefined,
      header: undefined,
      phone: undefined,
      email: undefined,
      status: CommonStatusEnum.ENABLE,
      targetIps: ''
    }
  ]
})
const keys = {
  parentId: '',
  name: undefined,
  cityId: undefined,
  orderIndex: undefined,
  address: undefined,
  header: undefined,
  phone: undefined,
  email: undefined,
  status: CommonStatusEnum.ENABLE,
  targetIps: ''
}
const delRow = (index) => {
  formData.list && formData.list.length > 0 && formData.list.splice(index, 1)
}
const addRow = (index) => {
  formData.list.push(cloneDeep(keys))
}

/** 获得系统树 */
const getTree = async () => {
  deptTree.value = []
  const data = await SystemApi.getInfoSystemPage({ pageSize: -1 })
  deptTree.value = handleTree(data)
}
/** 获取省市树 */
async function getAreaTree() {
  const res = await AreaApi.getAreaTree2()
  areaTree.value = res
}
async function getUserList() {
  userList.value = await UserApi.getSimpleUserList()
}

async function submit() {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  const { code } = await SystemApi.createBatchSystem(formData.list)
  if (code == 200) {
    ElMessage.success('创建成功')
    emit('close', true)
  }
}

const valideName = (rules, value, callBack) => {
  if (!value) {
    return callBack(new Error('系统名称不能为空'))
  }
  let index = 0
  formData.list.forEach((item) => {
    item.name == value && index++
  })
  index >= 2 ? callBack(new Error('系统名称不能重复')) : callBack()
}

const validateIp = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  const ipList = value.split('\n')
  const IPV4 =
    /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(\/(?:3[0-2]|[12]?[0-9]))?(-(?:25[0-5]|2[0-4]\d|[1]?\d\d?))?$/
  for (let ip of ipList) {
    if (!IPV4.test(ip)) {
      return callback(new Error('IP地址格式不正确'))
    } else if (ip.includes('-')) {
      const [start, end] = ip.split('-')
      const [one, two, three, four] = start.split('.')
      if (Number(four) >= Number(end)) {
        return callback(new Error('IP地址格式不正确'))
      }
    }
  }
  callback()
}
onMounted(async () => {
  getAreaTree()
  getTree()
  getUserList()
})
</script>

<style lang="scss" scoped></style>
